﻿pdfjsLib.GlobalWorkerOptions.workerSrc = "/lib/pdfjs-4.7.76-dist/build/pdf.worker.mjs";
const loadingTask = pdfjsLib.getDocument(path);
const pdf = await loadingTask.promise;
let viewEle1 = document.getElementById("page1");
let viewEle2 = document.getElementById("page2");
let viewEle1Con = document.getElementById("page1Con");
let viewEle2Con = document.getElementById("page2Con");
viewEle1Con.addEventListener("click", PrePage);
viewEle2Con.addEventListener("click", NextPage);

let currentPage = readPos;
let catalogs = await pdf.getOutline();
console.log(pdf.numPages);
for(let i = 0; i < catalogs.length; i++) {
    let pageNum = null;
    if (catalogs[i].dest) {
        pageNum = await pdf.getPageIndex(catalogs[i].dest[0]) + 1
    }
    insertChildElement("catalog", "li", catalogs[i].title, {className: "list-group-item", attributes: {'data-page-num': pageNum}, events: {click: catalogOnClick}});
}

await renderPage(currentPage, viewEle1, viewEle1Con);
await renderPage(currentPage + 1, viewEle2, viewEle2Con);

async function catalogOnClick(_this)
{
    let ele = _this.target;
    let num = ele.getAttribute("data-page-num");
    num = parseInt(num);
    currentPage = num;
    UploadReadPos(currentPage);
    await renderPage(currentPage, viewEle1, viewEle1Con);
    await renderPage(currentPage + 1, viewEle2, viewEle2Con);
}

async function renderPage(index, ele, eleCon) {
    let context = ele.getContext('2d');
    let page = await pdf.getPage(index);
    let viewport = page.getViewport({ scale: 1, });
    let canvasSize = {
        width: eleCon.getBoundingClientRect().width,
        height: eleCon.getBoundingClientRect().height
    }
    let pdfSize = {
        width: viewport.width,
        height: viewport.height
    }
    let ret = calculateScaling(pdfSize, canvasSize)
    console.log(ret)
    let scaleViewport = page.getViewport({ scale: ret.scale });
    ret.scale = window.devicePixelRatio || 1;
    var transform = ret.scale !== 1
        ? [ret.scale, 0, 0, ret.scale, 0, 0]
        : null;
    let renderContext = {
        canvasContext: context,
        viewport: scaleViewport
    };
    ele.width = ret.width;
    ele.height = ret.height;
    page.render(renderContext);
}

function PrePage()
{
    if(pdf == null)
        return;
    if(currentPage === 1)
        return;
    currentPage -= 2;
    UploadReadPos(currentPage);
    renderPage(currentPage, viewEle1, viewEle1Con);
    renderPage(currentPage + 1, viewEle2, viewEle2Con);
}

function NextPage()
{
    if(pdf == null)
        return;
    if(pdf == null)
        return;
    if(currentPage + 1 === pdf.numPages || currentPage === pdf.numPages)
        return;
    currentPage += 2;
    UploadReadPos(currentPage);
    renderPage(currentPage, viewEle1, viewEle1Con);
    renderPage(currentPage + 1, viewEle2, viewEle2Con);
}

function calculateScaling(originalSize, targetSize) {
    console.log("originalSize", originalSize)
    console.log("targetSize", targetSize)   
    const originalWidth = originalSize.width;
    const originalHeight = originalSize.height;
    const targetWidth = targetSize.width;
    const targetHeight = targetSize.height;

    // 计算宽度和高度的缩放比例
    const widthScale = targetWidth / originalWidth;
    const heightScale = targetHeight / originalHeight;

    // 选择较小的缩放比例
    const scale = Math.min(widthScale, heightScale);

    // 计算缩放后的尺寸
    const scaledWidth = originalWidth * scale;
    const scaledHeight = originalHeight * scale;

    return {
        width: scaledWidth,
        height: scaledHeight,
        scale: scale
    };
}

function insertChildElement(parentId, childTagName, childTextContent, config = {}) {
    // 获取父元素
    var parentElement = document.getElementById(parentId);

    // 检查父元素是否存在
    if (parentElement) {
        // 创建新的子元素
        var childElement = document.createElement(childTagName);

        // 设置子元素的文本内容
        if (childTextContent !== undefined) {
            childElement.textContent = childTextContent;
        }

        // 设置子元素的类名
        if (config.className) {
            childElement.className = config.className;
        }

        // 设置其他属性
        if (config.attributes) {
            for (var attr in config.attributes) {
                if (config.attributes.hasOwnProperty(attr)) {
                    childElement.setAttribute(attr, config.attributes[attr]);
                }
            }
        }

        // 添加事件监听器
        if (config.events) {
            for (var eventType in config.events) {
                if (config.events.hasOwnProperty(eventType)) {
                    childElement.addEventListener(eventType, config.events[eventType]);
                }
            }
        }

        // 将子元素添加到父元素中
        parentElement.appendChild(childElement);
    } else {
        console.error('Parent element with ID "' + parentId + '" not found.');
    }
}